package com.isoftstone.studentregistration.service.Impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.SecureUtil;


import cn.hutool.poi.excel.ExcelUtil;

import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.isoftstone.studentregistration.mapper.UserMapper;
import com.isoftstone.studentregistration.pojo.Users;
import com.isoftstone.studentregistration.service.UserService;
import com.isoftstone.studentregistration.util.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

//业务逻辑接口层实现类
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result<Users> queryUserByPhone(String phone) {
        Users user = userMapper.queryUserByPhone(phone);
        if (user != null) {
            return Result.fail("手机号已被注册");
        }
        return Result.success(user);
    }

    @Override
    public Result<?> insertUser(Users user) {
        Users users = userMapper.queryUserByPhone(user.getPhone());
        if (users == null) {
            //系统生成时间
            user.setCreateDate(new Date());
//           密码加密
            user.setPassword(new String(SecureUtil.md5(user.getPassword())));
            int insert = userMapper.insertUser(user);
            if (insert > 0) {
                return Result.success("添加成功");
            }
            return Result.fail("添加失败");
        }
        return Result.fail("手机号已被注册");
    }

    @Override
    public Result<?> updateUser(Users user) {
        // 1. 先处理参数（加密密码、设置更新时间），再执行数据库更新
        // 密码非空才加密（避免空值加密导致异常，或覆盖原有加密密码）
        if (user.getPassword() != null && !"".equals(user.getPassword().trim())) {
            // 注意：SecureUtil.md5返回的是16/32位字符串，无需转String（原代码new String()多余且可能乱码）
            user.setPassword(SecureUtil.md5(user.getPassword().trim()));
        }
        // 设置系统当前时间为更新时间（确保同步到数据库）
        user.setUpdateDate(new Date());

        // 2. 执行数据库更新操作（此时参数已处理完成）
        int result = userMapper.updateUser(user);

        // 3. 根据更新结果返回响应
        if (result > 0) {
            return Result.success("修改成功");
        }
        return Result.fail("修改失败（可能用户ID不存在或数据无变化）");
    }

    @Override
    public Result<?> deleteUser(Integer id) {
        int result = userMapper.deleteUser(id);
        if (result > 0) {
            return Result.success("删除成功");
        }
        return Result.fail("删除失败");
    }


//查询所有信息
@Override
public Page queryAllUsers(Integer currentPage, Integer pageSize) {
    Page<Users> page = PageHelper.startPage(currentPage, pageSize);
    List<Users> users = userMapper.queryAllUsers();
    return page;
}
//用户登录
    @Override
    public Result<?> login(String phone, String password) {
        Users user = userMapper.login(phone, new String(SecureUtil.md5(password)));
        return user==null ? Result.fail("用户名或密码错误") : Result.success(user);
    }

    @Override

    public void exportExcel(HttpServletResponse response) {
        List<Users> users = userMapper.queryAllUsers(); // 注意方法名小写
        try (ServletOutputStream os = response.getOutputStream();
             ExcelWriter writer = ExcelUtil.getWriter(true)) { // true 表示 .xlsx
            writer.write(users, true);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            String fileName = URLEncoder.encode("用户信息表", StandardCharsets.UTF_8.name());
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            writer.flush(os, true);
        } catch (IOException e) {
            log.error("导出Excel失败", e);
        }
    }

    //根据id批量删除
    @Override
    public Result<?> deleteBatch(List<Integer> ids) {
        int result = userMapper.deleteBatch(ids);
        if (result > 0) {
            return Result.success("删除成功");
        }
        return Result.fail("删除失败");
    }

    @Override
    public Result<Integer> updateStatus(Integer id, String status) {
        // 1. 参数校验
        if (id == null || id <= 0) {
            return Result.fail("用户 ID 非法");
        }
        if (status == null || status.trim().isEmpty()) {
            return Result.fail("状态值不能为空");
        }

        // 2. 落库
        int rows = userMapper.updateStatus(id, status);
        if (rows == 0) {
            return Result.fail("用户不存在或状态已相同");
        }

        // 3. 返回受影响行数
        return Result.success(rows);
    }
//根据状态或用户名分页
@Override
public PageInfo<Users> queryUsers(Integer status, String username, Integer currentPage, Integer pageSize) {
    // 1. 打印参数（确认currentPage和pageSize有值，不再是空）
    log.info("查询参数：status={}, username={}, currentPage={}, pageSize={}",
            status, username, currentPage, pageSize);

    // 2. 设置分页（PageHelper会自动拦截后续的查询SQL，添加LIMIT分页）
    PageHelper.startPage(currentPage, pageSize);

    // 3. 执行查询（此时返回的List已被PageHelper处理为分页数据）
    List<Users> userList = userMapper.queryUsers(status, username);

    // 4. 封装为PageInfo（包含总条数、总页数等分页信息，方便前端使用）
    PageInfo<Users> pageInfo = new PageInfo<>(userList);
    return pageInfo;
}


    @Override
    public void importTemplate(HttpServletResponse response) throws IOException {
        //1.创建ExcelWriter对象
        ExcelWriter writer = ExcelUtil.getWriter();
        //2.设置导入模板字段
        Map<String, Object> row = new LinkedHashMap<>();
        row.put("用户名称", "张三");
        row.put("登录密码", "123456");
        row.put("所属部门", "研发部");
        row.put("联系电话", "13928508520");
        row.put("用户状态", 1);
        List<Map<String, Object>> users = CollUtil.newArrayList(row);
        //3.将查询结果写入Excel
        writer.write(users, true);
        //4.设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户导入模板", "UTF-8");
        // 5.设置响应头信息
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        //获取输出流对象
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        //关闭流对象
        writer.close();
        IoUtil.close(out);
    }
}


